//
//  DecoratingVC.m
//  NewNest
//
//  Created by hesiyao on 16/1/19.
//  Copyright © 2016年 www.lanou3g.com蓝鸥科技. All rights reserved.
//

#import "DecoratingVC.h"
#import <AFNetworking.h>
#import <AFHTTPSessionManager.h>
#import "DecoratingModal.h"
#import "DecoratingCell.h"
#import <UIImageView+WebCache.h>
#import "DecoratingDetailPageVC.h"
#import <MJRefresh.h>
@interface DecoratingVC () <UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, retain) UICollectionView *collectionview;
@property (nonatomic, retain) NSMutableArray *dataArr;
@property (nonatomic, assign) NSInteger number;/**< 用来保存加载时动态值 */
@end

@implementation DecoratingVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // navigation
    self.navigationItem.title = @"正在装修";
    
    // 数据处理
    [self dataHandler];
    // 视图创建
    [self createSubviews];
    //给加载动态值赋初值
    self.number = 2;
    // 下拉刷新
    [self refresh];
}

/// 数据处理
- (void)dataHandler
{
    NSString *urlStr = @"http://v5.owner.mjbang.cn/api/live-shows/new-list?page=1&app_version=2.1.3&user_token=af9d7efbcf93fba063f4f45fbf442c73-111249-App%5CModels%5CMember&phone_type=iOS&limit=10&app_channel=appstore&imei=0ABFB620-74E5-4ADF-AA87-C92326CFA2CD&mark=1&app_type=Owner";
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"正在装修解析成功");
        NSMutableArray *arr = responseObject[@"data"];
        self.dataArr = [DecoratingModal modelHanderWithArray:arr];
        
        [_collectionview reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"正在解析失败");
    }];
    
    //下拉刷新结束
    [self.collectionview.mj_header endRefreshing];
}

/// 视图创建
- (void)createSubviews
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((self.view.frame.size.width - 30) / 2, self.view.frame.size.width / 3);
    self.collectionview = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    _collectionview.contentInset = UIEdgeInsetsMake(10, 10, 10, 10);
    _collectionview.backgroundColor = [UIColor whiteColor];
    _collectionview.delegate = self;
    _collectionview.dataSource = self;
    [_collectionview registerClass:[DecoratingCell class] forCellWithReuseIdentifier:@"cell"];
    [self.view addSubview:_collectionview];
    [_collectionview release];
    
}

/// 设置cell个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataArr.count;
}

/// 设置cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    DecoratingCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    if (_dataArr.count != 0) {
        DecoratingModal *m = _dataArr[indexPath.row];
        cell.titleLabel.text = m.title;
        NSString *str = [NSString stringWithFormat:@"%@㎡",m.acreage_property];
        cell.spaceLabel.text = str;
        cell.contentLabel.text = m.content;
        [cell.backImg sd_setImageWithURL:[NSURL URLWithString:m.imgStr]];
        return cell;
    }else{
        return cell;
    }
}

- (void)hidden
{
    // 导航栏隐藏设置
    if ([self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)]) {
        // 取消ScrollView的内容自动调整
        self.automaticallyAdjustsScrollViewInsets = NO;
        //tableView边界预留
        UIEdgeInsets insets = self.collectionview.contentInset;
        // 让上边界的预留值和导航栏相等
        insets.top = self.navigationController.navigationBar.bounds.size.height;
        //把修改后的边界预留值赋给tableView
        self.collectionview.contentInset = insets;
        // 滚动指标点到滚到视图的边缘的距离
        self.collectionview.scrollIndicatorInsets = insets;
    }
}

// 导航栏滚动
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    if (velocity.y > 0) {
        self.navigationController.navigationBar.hidden = YES;
        self.tabBarController.tabBar.hidden = YES;
    }else{
        self.navigationController.navigationBar.hidden = NO;
        self.tabBarController.tabBar.hidden = NO;
    }
}

// 点击进入详情页面
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    DecoratingDetailPageVC *detailVC = [[DecoratingDetailPageVC alloc] init];
    DecoratingModal *m = _dataArr[indexPath.item];
    detailVC.detailId = m.detailId;
    [self.navigationController pushViewController:detailVC animated:YES];
}

// 下拉刷新 上拉加载
- (void)refresh
{
    // 下拉刷新
    self.collectionview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(dataHandler)];
    [self.collectionview.mj_header beginRefreshing];
    
    // 上拉加载
    self.collectionview.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    //判断数据数组不为空 加载新数据
    if (_dataArr.count != 0 || self.number <= 3) {
        [self.collectionview.mj_footer beginRefreshing];
    }
}

/// 上拉加载方法
- (void)loadNewData
{
    NSString *firstStr = @"http://v5.owner.mjbang.cn/api/live-shows/new-list?page=";
    NSString *secondStr = @"&app_version=2.1.6&user_token=af9d7efbcf93fba063f4f45fbf442c73-111249-App%5CModels%5CMember&phone_type=iOS&limit=10&app_channel=appstore&imei=0ABFB620-74E5-4ADF-AA87-C92326CFA2CD&mark=1&app_type=Owner";
    NSString *urlStr = [NSString stringWithFormat:@"%@%ld%@", firstStr, self.number, secondStr];
    [[AFHTTPSessionManager manager] GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //创建新数组保存新数据
        NSArray *newDataArr = [NSArray array];
        newDataArr = [DecoratingModal modelHanderWithArray:responseObject[@"data"]];
        //将新的数据依次加到数据数组里面
        for (NSInteger i = 0; i < newDataArr.count; i++) {
            [_dataArr addObject:newDataArr[i]];
        }
        // 刷新collectionview
        [self.collectionview reloadData];
        NSLog(@"正在装修加载成功");
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"正在装修加载失败");
    }];
    
    // 结束上拉刷新
    [self.collectionview.mj_footer endRefreshing];
   
        self.number += 1;
    

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
